package com.chx.ajxtest.controller;

import com.chx.ajxtest.bean.Travel;
import com.chx.ajxtest.commom.ResultInfo;
import com.chx.ajxtest.service.TravelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


//@Controller
//@ResponseBody //类注解，对类中所有方法有效
@RestController
@CrossOrigin
public class TravelController {
    @Autowired
    private TravelService travelService;

    @GetMapping("/travels")
    public ResultInfo findAll(@RequestParam("id") Integer id) {
        ResultInfo ri = new ResultInfo();
        try {
            List<Travel> travels = travelService.queryAll(id);
            ri.setOk();
            ri.setData(travels);
        } catch (Exception e) {
            ri.setError();
            e.printStackTrace();
        }
        return ri;
    }

    @DeleteMapping("/travels/{sid}")
    public ResultInfo deleteById(@PathVariable("sid") Integer id) {
        ResultInfo ri = new ResultInfo();
        System.out.println(id);
        try {
            travelService.deleteById(id);
            ri.setOk();
        } catch (Exception e) {
            ri.setError();
            e.printStackTrace();
        }
        return ri;
    }

    @PostMapping("/travels/add")
    public ResultInfo add(Travel travel) {
        ResultInfo ri = new ResultInfo();
        try {
            travelService.add(travel);
            ri.setOk();
        } catch (Exception e) {
            ri.setError();
            e.printStackTrace();
        }
        return ri;
    }

    @PutMapping("/travels/update")
    public ResultInfo update(Travel travel) {
        ResultInfo re = new ResultInfo();
        try {
            travelService.update(travel);
            re.setOk();
        } catch (Exception e) {
            re.setError();
            e.printStackTrace();
        }
        return re;
    }

}
